import socket
import json
import threading
import time

serverIP='192.168.56.104'
remoteIP='192.168.56.105'
buffer_size=1024
local_addr=('192.168.56.1',6666)

print('Please choose your operation:')
print('1 chat')
print('2 file transfer')

class recvFile(threading.Thread):
    def __init__(self,path,sock):
        threading.Thread.__init__(self)
        self.sock=sock
        self.path=path

    def run(self):
        recv=self.sock.recv(buffer_size).decode()
        recv=json.loads(recv)

        print(recv)
        
        if recv['status code']==200:
            size=recv['content-length']
            file=open(self.path,'wb')
            cnt=0
            t=time.time()

            while cnt<size:
                data=self.sock.recv(buffer_size)
                file.write(data)
                cnt+=len(data)
            t=time.time()-t
            print('Download succeed, total time: {} second(s)'.format(t))
            file.close()
            self.sock.close()
        
        else:
            print('File transfer failed!')
            self.sock.close()


class myDaemon(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        daemon=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        daemon.bind(local_addr)
        daemon.listen()

        while True:
            conn,address=daemon.accept()
            recv=conn.recv(buffer_size).decode()
            message=json.loads(recv)
            print('\nFrom {}:\n{}\n'.format(message['source'],message['message']))
        daemon.close()

class waitingInput(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            option=''
            while True:
                option=input('Please input option:\n')
                try:
                    option=int(option)
                except:
                    print("Bad input!")
                else:
                    break

            sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            sock.connect((serverIP,8080))

            if option==1:
                message=input('Please input message:\n')
                # message='hello,192.168.56.106!'
                request={'request-type':'1','request-body':{'address':remoteIP,'message':message}}
                request=json.dumps(request).encode()
                sock.send(request)
                sock.close()
            elif option==2:
                path='test.mp4'
                request=json.dumps({'request-type':0,'request-body':{'path':'content/'+path}}).encode()
                sock.send(request)
                fileTransfer=recvFile(path,sock)
                fileTransfer.start()

daemon=myDaemon()
daemon.start()

collect=waitingInput()
collect.start()